package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.StockBackService;
import com.qingcheng.service.order.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-07-20
 * Time: 21:32
 */
@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService {

    @Autowired
    private StockBackMapper stockBackMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Override
    @Transactional
    public void addList(List<OrderItem> orderItemList) {

        for (OrderItem orderItem : orderItemList) {

            StockBack stockBack = new StockBack();
            stockBack.setNum(orderItem.getNum());
            stockBack.setCreateTime(new Date());
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setStatus("0");
            stockBackMapper.insert(stockBack);
        }
    }

    @Override
    public void doBack() {
        System.out.println("回滚开始");
        StockBack stockBack = new StockBack();
        stockBack.setStatus("0");
        List<StockBack> stockBackList = stockBackMapper.select(stockBack);
        for (StockBack stock : stockBackList) {
            skuMapper.addSaleNum(stock.getSkuId(), -stock.getNum());
            skuMapper.deductionStock(stock.getSkuId(), -stock.getNum());

            stock.setStatus("1");
            stock.setBackTime(new Date());

            stockBackMapper.updateByPrimaryKey(stock);
        }
        System.out.println("回滚结束");
    }
}
